<?php
   
namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;


use App\Model\Cat;
use DB;
class IndexController extends Controller
{
    /**  
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $Cat = new Cat();
        $datas = $Cat::select('cat_id','parent_id','cat_name')->get();
        $tops = $Cat->findSon($datas,0);
        $cats = $Cat->findAll();
       //$sogos = DB::table('merchant')->get();

        if(!empty($_SESSION['userInfo'])){
            $id = $_SESSION['userInfo']['id'];
            $x = DB::table('user_info')->where('uid',$id)->first();
            if(!$x){
                 $x = !empty($_POST['address'])?($_POST['address']):"";
            }

        }else{
       $x = !empty($_POST['address'])?($_POST['address']):"";
            }
       if($x){
       $sogos= $this->lst($x);
            }else{
                $sogos = DB::table('merchant')->where('state','1')->get();
            }



        //return view('home.index',['sogos'=>$sogos]);




        return view('home.index')->with('cats',$cats)->with('tops',$tops)->with('sogos',$sogos);

    }

    // public function sogos()
    // {
    //     $sogos = DB::table('merchant')->get();

    //     dd($sogos);
    // }



                       // 根据地址信息遍历首页的商品
                
            public function lst($x){

                 $key = '1d6577a66716940f16fabe795e5c8dd0';
            if(($x)){

            $a = file_get_contents('http://restapi.amap.com/v3/geocode/geo?key='."{$key}".'&address='."{$x}");
          $a= json_decode($a);
          $cadta = ($a->geocodes['0']->location);
          $arr = explode(",", $cadta); 
                 }

                 $src = DB::table('merchant')->select('id','cdata')->where('state','1')->get();
                 foreach($src as $s){
                    $c = explode(",",$s->cdata);
                    if(abs($arr['0']-$c['0'])<0.03 && abs($arr['1']-$c['1'])<0.03){
                            static $data;
                            $data[] = DB::table('merchant')->where('id',$s->id)->first();

                    }
                 }
                 return $data;
            }
}
